package com.liuzhou.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.liuzhou.dao.UserDao;
import com.liuzhou.dao.impl.UserDaoImpl;
import com.liuzhou.model.User;

public class LoginAction extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// 获取页面数据
		String userName = req.getParameter("username");//
		String password = req.getParameter("password");
		String authcode = req.getParameter("authcode");// 获取用户验证码答案

		// 将合法用户放入session中 -> Map<String, Object>
		HttpSession session = req.getSession();

		// 验证码正确性验证
		String authCodeAnswer = (String) session.getAttribute("authcode");
		if (authCodeAnswer != null && authCodeAnswer.equals(authcode)) {// 用户答对了
			System.out.println("验证码输入正确，开始验证账户密码");
			// 数据验证 不写了
			try {
				// 登录验证处理 ->
				User user = new User();
				user.setName(userName);
				user.setPassword(password);
				UserDao ud = new UserDaoImpl();
				User result = ud.queryUser(user);

				if (result == null) {// 用户不合法
					System.out.println("用户名或密码错误，请重新输入");
					 
					// 将登录的信息绑定在request作用域中，只在登录页面提示就可以了
//					req.setAttribute("loginMsg", "用户名或密码错误!");					
//					req.getRequestDispatcher("/try.jsp").forward(req, resp);
					session.setAttribute("loginMsg", "用户名或密码错误，请重新输入");					
					resp.sendRedirect("indexPage.action");//用户名不合法，重新定向到登录
					return;
				} else {// 合法用户
//					req.setAttribute("loginMsg", "用户已登录成功!");
//					req.getRequestDispatcher("/try.jsp").forward(req, resp);
					session.setAttribute("loginMsg", "用户已登录成功!");
					session.setAttribute("loginUser", result);// 记录登录状态					
					resp.sendRedirect("indexPage.action");// 转到主页
					//TODO 退出登录时还需改变 Session状态
					return;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

		} else {//用
			System.out.println("验证码输入有错误，请重新输入");
//			req.getRequestDispatcher("/try.jsp").forward(req, resp);
			session.setAttribute("loginMsg", "验证码输入有错误，请重新输入");
//			req.setAttribute("loginMsg", "验证码输入有错误，请重新输入");
			resp.sendRedirect("indexPage.action");//验证码不合法，重新定向到登录
			
		}
	}

}
